package team.bluepen.supermarket.web.servlet;

import team.bluepen.supermarket.constant.Constant;
import team.bluepen.supermarket.constant.Error;
import team.bluepen.supermarket.data.hbase.GoodsLineReader;
import team.bluepen.supermarket.data.hdfs.TableFileReadRunner;
import team.bluepen.supermarket.util.Log;
import team.bluepen.supermarket.util.StringUtil;
import team.bluepen.supermarket.web.base.BaseServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * hdfs MapReduce
 * @author Kai
 */
@WebServlet(name = "FileReadServlet", urlPatterns = "/api/file-read")
public class FileReadServlet extends BaseServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path = req.getParameter("path");
        String type = req.getParameter("type");
        String fileType = req.getParameter("file_type");

        if (StringUtil.isEmpty(path) || StringUtil.isEmpty(type)) {
            sendRedirect(resp, Error.ERROR_NULL);
            return;
        }

        if (!"good".equalsIgnoreCase(type)) {
            sendRedirect(resp, Error.ERROR_ILLEGAL_STATE);
            return;
        }

        if (!"good".equalsIgnoreCase(fileType)) {
            resp.sendRedirect("/loading.html");
            return;
        }

        TableFileReadRunner fileReader = new TableFileReadRunner(path);

        boolean s;
        try {
            s = fileReader.startJob(Constant.GoodTable.TABLE_NAME, GoodsLineReader.GoodsTableMapper.class);
            Log.w("HDFS", "state of processing: " + s);
        } catch (Exception e) {
            s = false;
            Log.e("HDFS", e);
        }
        Error state = s ? Error.SUCCESS : Error.ERROR_IO;
        sendRedirect(resp, state);
    }

    private static void sendRedirect(HttpServletResponse resp, Error error) throws IOException {
        resp.sendRedirect("/file.jsp?error=" + error.getValue());
    }
}
